// stores/currency.ts
import {defineStore} from 'pinia'
import {getRateList} from "../api";
import { Local } from "@/utils/storage.ts";
interface Currency {
    id: string | number
    name: string
    unit: string
    cn_name: string
    currency_code: string,
    exchange_rate: number,
}
export const useCurrencyStore = defineStore('currency', {
    state: () => ({
        currentCurrency: Local.get('currentCurrency') || { unit: '$' } as Currency,
        currencies: Local.get('currencies') || [] as Currency[],
    }),
    actions: {
        async fetchCurrencies() {
            // 如果已经有了，就不再请求了
            // if(Local.get('currencies')){
            //     return;
            // }
            await getRateList().then((res) => {
                if (res.code === 200) {
                    let arr = res.data.map((item: any) => ({
                        value: item.id,
                        label: item.name,
                        unit: item.unit,
                        cn_name: item.cn_name,
                        currency_code: item.currency_code,
                        exchange_rate: item.exchange_rate
                    }))
                    this.setCurrencies(arr)
                    if(arr?.length > 0){
                        this.setCurrency(arr[0])
                    }
                    
                }
            })
        },
        setCurrency(currency: Currency) {
            this.currentCurrency = currency
            Local.set('currentCurrency', currency)
        },
        setCurrencies(currencies: Array<Currency>) {
            this.currencies = currencies
            Local.set('currencies', currencies)
        },
    },
})
